<?php
namespace App\Models;

class Admin extends Model
{
    protected $tableName = 'admin';
    protected $pk = 'id';

    protected $_validate = array(
            array('username','require','用户名称不能为空'),
            array('nickname','require','用户昵称不能为空'),
        );        

    //自动完成
    protected $_auto = array (
            array('createtime','gettime',1,'callback'),
            array('updatetime','gettime',1,'callback'),
        );

    protected $_map = array(
            // 'name' =>'username', // 把表单中name映射到数据表的username字段
            // 'mail'  =>'email', // 把表单中的mail映射到数据表的email字段
        );
    
	/**
     * 校验用户登录
     * @param type $username 111
     * @param type $userpwd
     * @param type $vcode
     * @throws \Exception
     */
    public function checkLogin($username,$userpwd,$vcode)
    {
        if (strtolower($vcode)!== $_SESSION['captcha']){
            throw new \Exception("验证码不正确",'001');
        }
        if ($username==""||$userpwd==""){
            throw new \Exception("用户名或密码不能为空",'002');
        }
        
        $data = array( '`status`'=>'normal'  ,'username'=>$username );
        $result = $this->field('id,username,nickname,avatar,email,group_id,password,salt')->where($data)->find();
        if ($result)
        {
            if ($result['password']==mymd5($userpwd,$result['salt']))
            {
                $_SESSION['uid'] = $result['id'];
                $_SESSION['username'] = $result['username'];
                $_SESSION['nickname'] = $result['nickname'];
                $_SESSION['email']    = $result['email'];
                $_SESSION['avatar']   = $result['avatar'];
                $_SESSION['group_id'] = $result['group_id'];
                unset($result['password']);
                unset($result['salt']);
                return $result;
            } else {
                throw new \Exception("密码不正确",'003');
            }
        } else {
            throw new \Exception("没有找到账号{$username}用户",'004');
        }
    } 

}
